package com.bpmn.config;

import cn.hutool.core.collection.ListUtil;
import com.bpmn.flow.behavior.BpmActivityBehaviorFactory;
import com.bpmn.flow.behavior.BpmTaskCandidateInvoker;
import com.bpmn.flow.handler.TaskTimeoutJobHandler;
import com.bpmn.flow.listener.BpmProcessInstanceEventListener;
import com.bpmn.flow.listener.BpmTaskEventListener;
import com.bpmn.flow.service.TaskOperationService;
import jakarta.annotation.Resource;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.flowable.spring.boot.EngineConfigurationConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;


/**
 * flowable配置
 *
 * @author may
 */
@Configuration
public class FlowableConfig implements EngineConfigurationConfigurer<SpringProcessEngineConfiguration> {

    @Resource
    private BpmProcessInstanceEventListener processInstanceEventListener;

    @Resource
    private BpmTaskEventListener taskEventListener;

    @Resource
    private BpmTaskCandidateInvoker bpmTaskCandidateInvoker;

    @Resource
    @Lazy
    private TaskOperationService taskOperationService;

    @Override
    public void configure(SpringProcessEngineConfiguration processEngineConfiguration) {
        // 注册监听器
        processEngineConfiguration.setEventListeners(ListUtil.of(processInstanceEventListener, taskEventListener));
        // 设置 ActivityBehaviorFactory 实现类，用于流程任务的审核人的自定义
        processEngineConfiguration.setActivityBehaviorFactory(bpmActivityBehaviorFactory(bpmTaskCandidateInvoker));
        //设置超时任务定时器
        processEngineConfiguration.addCustomJobHandler(new TaskTimeoutJobHandler(taskOperationService));
    }

    @Bean
    public BpmActivityBehaviorFactory bpmActivityBehaviorFactory(BpmTaskCandidateInvoker bpmTaskCandidateInvoker) {
        BpmActivityBehaviorFactory bpmActivityBehaviorFactory = new BpmActivityBehaviorFactory();
        bpmActivityBehaviorFactory.setTaskCandidateInvoker(bpmTaskCandidateInvoker);
        return bpmActivityBehaviorFactory;
    }

}
